/**************************************************************
 *@ProjectName: blweibo
 *@FileName: HomeListActivity.java
 *@Date: 2011-5-31
 *@Copyright: 2011 www.hrbanlv.com Inc. All rights reserved.
 **************************************************************/
package com.zhiweibo;

import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.AsyncTask.Status;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.zhiweibo.models.StaticInfo;
import com.zhiweibo.models.Topic;
import com.zhiweibo.util.Constant;
import com.zhiweibo.util.Helper;
import com.zhiweibo.util.HttpUtil;

/**
 * The Class HomeListActivity.
 * 
 * @author SunHaibin
 * @since Android 1.6
 * @history 2011-5-31
 */
public class HomeListActivity extends HomeListBaseActivity implements OnItemClickListener, OnItemLongClickListener,
        OnClickListener {

    /** The m list. */
    public List<Topic> mList = new ArrayList<Topic>();

    /** The mlv. */
    private ListView mlv;

    /** The tv title bar info. */
    protected TextView tvTitleBarInfo;

    /** The adapter. */
    private BaseAdapter adapter;

    /** The m page. */
    private int mPage = 1;

    /** The m back list. */
    private List<Topic> mBackList = new ArrayList<Topic>();

    /** The wd. */
    private WeiboDB wd;

    /** The m topic. */
    private Topic mTopic;

    /** The select. */
    private int select;

    /** The new_id. */
    public static String new_id = "0";

    /** The share items. */
    private String[] shareItems;

    /** The share dialog. */
    private Dialog shareDialog;

    /** The m task. */
    private AsyncTask mTask;

    /**
     * Load more.
     */
    private void loadMore() {
        mPage += 1;
        reloadBegine(0);
        if (mTask != null && mTask.getStatus() == Status.RUNNING) {
            mTask.cancel(true);
        }
        mTask = new HomeTask().execute(0);
    }

    /**
     * Reload.
     */
    private void reload() {
        reloadBegine(1);
        mlv.setSelection(0);
        mPage = 1;
        mBackList.clear();
        if (mTask != null && mTask.getStatus() == Status.RUNNING) {
            mTask.cancel(true);
        }
        mTask = new HomeTask().execute(0);
    }

    /*
     * (non-Javadoc)
     * 
     * @see com.yingnet.zhiweibo.BaseActivity#onCreate(android.os.Bundle)
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setView(R.layout.listbase);
        setTitleBar(1, getString(R.string.main_edit), StaticInfo.mNickName, getString(R.string.main_reload));
        tvTitleBarInfo = (TextView) findViewById(R.id.titleText);
        wd = WeiboDB.getInstance(HomeListActivity.this);
        mlv = (ListView) findViewById(R.id.lvUser);
        adapter = new WeiboListAdapter();
        mlv.setAdapter(adapter);
        mlv.setOnItemClickListener(this);
        mlv.setOnItemLongClickListener(this);
        tvTitleBarInfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View paramView) {
                if ((mList != null) && (mList.size() != 0)) {
                    mlv.setSelection(0);
                }
            }
        });
        new DBTask().execute(0);
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * android.widget.AdapterView.OnItemClickListener#onItemClick(android.widget
     * .AdapterView, android.view.View, int, long)
     */
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (view == mReloadItem) {
            reload();
        } else if (view == mLoadmoreItem) {
            loadMore();
        } else {
            position--;
            select = position;
            startActivityForResult(
                    new Intent(HomeListActivity.this, DetailWeiboActivity.class).putExtra("topic", mList.get(position)),
                    100);
        }
    }

    /*
     * (non-Javadoc)
     * 
     * @see android.app.Activity#onActivityResult(int, int,
     * android.content.Intent)
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 100 && resultCode == -1) {
            mList.remove(select);
            mBackList.remove(select);
            adapter.notifyDataSetChanged();
        }
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * android.widget.AdapterView.OnItemLongClickListener#onItemLongClick(android
     * .widget.AdapterView, android.view.View, int, long)
     */
    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        if (view != mReloadItem && view != mLoadmoreItem) {
            position--;
            select = position;
            List lst = new ArrayList();
            mTopic = mList.get(position);
            lst.add(getString(R.string.comment));
            lst.add(getString(R.string.forward));
            lst.add(getString(R.string.share));
            if (mTopic.getFavorited()) {
                lst.add(getString(R.string.itemmenu_bookmark_del));
            } else {
                lst.add(getString(R.string.itemmenu_bookmark));
            }
            if (mTopic.getUser().getUid().equals(StaticInfo.mUid)) {
                lst.add(getString(R.string.itemmenu_delete));
            }
            if (!TextUtils.isEmpty(mTopic.getRetopic().getTid())) {
                lst.add(getString(R.string.itemmenu_ori_mblog));
                lst.add(getString(R.string.itemmenu_forward_original));
            }
            lst.add(String.format(getString(R.string.view_one), mTopic.getUser().getUsername()));
            lst.add(getString(R.string.cancel));
            showMenu(lst);
        }
        return false;
    }

    /**
     * Show menu.
     * 
     * @param localList
     *            the local list
     */
    private void showMenu(final List localList) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.item_menu_title);
        CharSequence[] arrayOfCharSequence1 = new CharSequence[0];
        CharSequence[] arrayOfCharSequence2 = (CharSequence[]) localList.toArray(arrayOfCharSequence1);
        builder.setItems(arrayOfCharSequence2, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                String str = (String) localList.get(paramInt);
                doItemMenu(str);
            }
        });
        builder.create().show();
    }

    /**
     * Do item menu.
     * 
     * @param str
     *            the str
     */
    private void doItemMenu(String str) {
        if (str.equals(getString(R.string.comment))) {
            Intent intent = new Intent(HomeListActivity.this, EditActivity.class);
            intent.putExtra("mode", 1);
            intent.putExtra("topicId", mTopic.getTid());
            startActivity(intent);
        } else if (str.equals(getString(R.string.forward))) {
            Intent intent = new Intent(HomeListActivity.this, EditActivity.class);
            intent.putExtra("mode", 2);
            intent.putExtra("topicId", mTopic.getTid());
            if (!TextUtils.isEmpty(mTopic.getRetopic().getTid())) {
                intent.putExtra("content", "//@" + mTopic.getUser().getUsername() + ":" + mTopic.getHText());
            }
            startActivity(intent);
        } else if (str.equals(getString(R.string.share))) {
            showDialog(1);
        } else if (str.equals(getString(R.string.itemmenu_bookmark_del))) {
            new FavTask().execute(0);
        } else if (str.equals(getString(R.string.itemmenu_bookmark))) {
            new FavTask().execute(0);
        } else if (str.equals(getString(R.string.itemmenu_delete))) {
            new DeleteWeiboTask().execute(0);
        } else if (str.equals(String.format(getString(R.string.view_one), mTopic.getUser().getUsername()))) {
            startActivity(new Intent(HomeListActivity.this, UserInfoActivity2.class).putExtra("user", mTopic.getUser()));
        } else if (str.equals(getString(R.string.itemmenu_ori_mblog))) {
            startActivity(new Intent(HomeListActivity.this, DetailWeiboActivity.class).putExtra("topic",
                    mTopic.getRetopic()));
        } else if (str.equals(getString(R.string.itemmenu_forward_original))) {
            Intent intent = new Intent(HomeListActivity.this, EditActivity.class);
            intent.putExtra("mode", 2);
            intent.putExtra("topicId", mTopic.getRetopic().getTid());
            startActivity(intent);
        } else if (str.equals(getString(R.string.cancel))) {
        }
    }

    /*
     * (non-Javadoc)
     * 
     * @see android.app.Activity#onCreateDialog(int)
     */
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case 1:
            shareItems = getResources().getStringArray(R.array.share_dialog_list);
            shareDialog = new AlertDialog.Builder(this).setItems(shareItems, this).setTitle(R.string.share).create();
            return shareDialog;
        }
        return null;
    }

    /*
     * (non-Javadoc)
     * 
     * @see android.app.Activity#onResume()
     */
    @Override
    protected void onResume() {
        super.onResume();
        if (!tvTitleBarInfo.getText().toString().equals(StaticInfo.mNickName)) {
            setTitleBar(1, getString(R.string.main_edit), StaticInfo.mNickName, getString(R.string.main_reload));
            reload();
        }
    }

    /*
     * (non-Javadoc)
     * 
     * @see com.yingnet.zhiweibo.HomeListBaseActivity#handleTitleBarEvent(int)
     */
    @Override
    protected void handleTitleBarEvent(int paramInt) {
        switch (paramInt) {
        case 1:
            startActivity(new Intent(HomeListActivity.this, EditActivity.class).putExtra("mode", 0));
            break;
        case 0:
            reload();
            break;
        }

    }

    /**
     * The Class DBTask.
     * 
     * @author SunHaibin
     * @since Android 1.6
     * @history 2011-5-31
     */
    class DBTask extends AsyncTask<Object, Integer, List> {

        /*
         * (non-Javadoc)
         * 
         * @see android.os.AsyncTask#doInBackground(Params[])
         */
        @Override
        protected List doInBackground(Object... params) {
            mList = wd.selectTopic();
            if (mList == null || mList.size() == 0) {
                mList = HttpUtil
                        .getTopics(HomeListActivity.this, Constant.FRIENDS_TIMELINE + "?count=50&page=" + mPage);
                wd.deleteAllTopic();
                wd.insertTopic(mList);
            }
            if (mList != null && mList.size() > 0) {
                new_id = mList.get(0).getTid();
                Helper.saveString(HomeListActivity.this, "newId", new_id);
            }
            return mList;
        }

        /*
         * (non-Javadoc)
         * 
         * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
         */
        @Override
        protected void onPostExecute(List result) {
            mBackList.clear();
            mBackList.addAll(mList);
            adapter.notifyDataSetChanged();
            reloadEnd();
        }

        /*
         * (non-Javadoc)
         * 
         * @see android.os.AsyncTask#onPreExecute()
         */
        @Override
        protected void onPreExecute() {
            reloadBegine(1);
        }
    }

    /**
     * The Class HomeTask.
     * 
     * @author SunHaibin
     * @since Android 1.6
     * @history 2011-5-31
     */
    class HomeTask extends AsyncTask<Object, Integer, List> {

        /*
         * (non-Javadoc)
         * 
         * @see android.os.AsyncTask#doInBackground(Params[])
         */
        @Override
        protected List doInBackground(Object... paramArrayOfString) {
            String strUrl = Constant.FRIENDS_TIMELINE + "?count=50&page=" + mPage;
            mList = HttpUtil.getTopics(HomeListActivity.this, strUrl);
            return mList;
        }

        /*
         * (non-Javadoc)
         * 
         * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
         */
        @Override
        protected void onPostExecute(List result) {
            for (int i = 0; i < mList.size(); i++) {
                boolean b1 = true;
                Topic t1 = mList.get(i);
                for (int j = 0; j < mBackList.size(); j++) {
                    Topic t2 = mBackList.get(j);
                    if (t1.getTid().equals(t2.getTid())) {
                        b1 = false;
                        break;
                    }
                }
                if (b1) {
                    mBackList.add(t1);
                }
            }
            if (mPage == 1 && mList != null && mList.size() > 0) {
                new_id = mList.get(0).getTid();
                Helper.saveString(HomeListActivity.this, "newId", new_id);
                Message m = new Message();
                m.what = 0;
                MainTabActivity.handle.handleMessage(m);
                wd.deleteAllTopic();
                wd.insertTopic(mBackList);
            }
            mList.clear();
            mList.addAll(mBackList);
            adapter.notifyDataSetChanged();
            reloadEnd();
        }

    }

    /**
     * The Class WeiboListAdapter.
     * 
     * @author SunHaibin
     * @since Android 1.6
     * @history 2011-5-31
     */
    class WeiboListAdapter extends BaseAdapter {

        /*
         * (non-Javadoc)
         * 
         * @see android.widget.Adapter#getCount()
         */
        @Override
        public int getCount() {
            if (mList == null || mList.size() == 0) {
                return 1;
            } else {
                return mList.size() + 2;
            }
        }

        /*
         * (non-Javadoc)
         * 
         * @see android.widget.Adapter#getItem(int)
         */
        @Override
        public Object getItem(int paramInt) {
            return paramInt;
        }

        /*
         * (non-Javadoc)
         * 
         * @see android.widget.Adapter#getItemId(int)
         */
        @Override
        public long getItemId(int paramInt) {
            return paramInt;
        }

        /*
         * (non-Javadoc)
         * 
         * @see android.widget.Adapter#getView(int, android.view.View,
         * android.view.ViewGroup)
         */
        @Override
        public View getView(int paramInt, View paramView, ViewGroup paramViewGroup) {

            if (mList == null || mList.size() == 0) {
                return mReloadItem;
            } else {
                paramInt--;
                if (paramInt == -1) {
                    return mReloadItem;
                } else if (paramInt == mList.size()) {
                    return mLoadmoreItem;
                } else {
                    try {
                        if (paramView != null && paramView instanceof MBlogListItemView) {
                            ((MBlogListItemView) paramView).update(HomeListActivity.this, mList.get(paramInt));
                            return paramView;
                        } else {
                            return new MBlogListItemView(HomeListActivity.this, mList.get(paramInt));
                        }
                    } catch (Exception e) {
                        return null;
                    }
                }
            }
        }

        /*
         * (non-Javadoc)
         * 
         * @see android.widget.BaseAdapter#getViewTypeCount()
         */
        @Override
        public int getViewTypeCount() {
            if (mList == null) {
                return 1;
            } else {
                return 4;
            }
        }

        /**
         * Refresh.
         */
        public void refresh() {
            notifyDataSetChanged();
        }
    }

    /**
     * The Class FavTask.
     * 
     * @author SunHaibin
     * @since Android 1.6
     * @history 2011-5-31
     */
    class FavTask extends AsyncTask<Object, Integer, Object> {

        /** The pd. */
        private ProgressDialog pd;

        /*
         * (non-Javadoc)
         * 
         * @see android.os.AsyncTask#doInBackground(Params[])
         */
        @Override
        protected Object doInBackground(Object... params) {
            if (mTopic.getFavorited()) {
                HttpUtil.exeUrl(HomeListActivity.this, Constant.FAVORITES_DESTROY + mTopic.getTid() + ".json");
            } else {
                HttpUtil.exeUrl(HomeListActivity.this, Constant.FAVORITES_CREATE + "?tid=" + mTopic.getTid());
            }
            return null;
        }

        /*
         * (non-Javadoc)
         * 
         * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
         */
        @Override
        protected void onPostExecute(Object result) {
            mTopic.setFavorited(!mTopic.getFavorited());
            if (pd != null) {
                pd.dismiss();
            }
        }

        /*
         * (non-Javadoc)
         * 
         * @see android.os.AsyncTask#onPreExecute()
         */
        @Override
        protected void onPreExecute() {
            pd = new ProgressDialog(HomeListActivity.this);
            pd.setMessage("请稍候……");
            pd.show();
        }

    }

    /**
     * The Class DeleteWeiboTask.
     * 
     * @author SunHaibin
     * @since Android 1.6
     * @history 2011-5-31
     */
    class DeleteWeiboTask extends AsyncTask<Object, Integer, Boolean> {

        /** The pd. */
        private ProgressDialog pd;

        /*
         * (non-Javadoc)
         * 
         * @see android.os.AsyncTask#doInBackground(Params[])
         */
        @Override
        protected Boolean doInBackground(Object... paramArrayOfVoid) {
            String str = HttpUtil.exeUrl(HomeListActivity.this, Constant.DESTROY + mTopic.getTid() + ".json");
            return str.contains("1");
        }

        /*
         * (non-Javadoc)
         * 
         * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
         */
        @Override
        protected void onPostExecute(Boolean paramBoolean) {
            if (paramBoolean) {
                wd.deleteTopic(mList.get(select).getTid());
                mList.remove(select);
                mBackList.remove(select);
                adapter.notifyDataSetChanged();
                Toast.makeText(HomeListActivity.this, R.string.succeed_to_delete_weibo, Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(HomeListActivity.this, R.string.fail_to_delete_weibo, Toast.LENGTH_SHORT).show();
            }
            if (pd != null) {
                pd.dismiss();
            }
        }

        /*
         * (non-Javadoc)
         * 
         * @see android.os.AsyncTask#onPreExecute()
         */
        @Override
        protected void onPreExecute() {
            pd = new ProgressDialog(HomeListActivity.this);
            pd.setMessage("请稍候……");
            pd.show();
        }
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * android.content.DialogInterface.OnClickListener#onClick(android.content
     * .DialogInterface, int)
     */
    @Override
    public void onClick(DialogInterface dialog, int which) {
        if (shareDialog == dialog) {
            String strA = "@%s:%s\n";
            String strB = "图片地址:";
            String strC = getString(R.string.weibo_host);
            String str2 = shareItems[which];
            if (str2.equals(getString(R.string.short_message))) {
                Uri.Builder localBuilder = new Uri.Builder();
                localBuilder.scheme("sms");
                Uri localUri = localBuilder.build();
                Intent localIntent = new Intent("android.intent.action.SENDTO", localUri);
                StringBuilder sb = new StringBuilder();
                sb.append(String.format(strA, mTopic.getUser().getUsername(), mTopic.getHText()));
                if (!TextUtils.isEmpty(mTopic.getPic_a())) {
                    sb.append(strB).append(mTopic.getPic_a()).append("\n");
                }
                if (!TextUtils.isEmpty(mTopic.getRetopic().getTid())) {
                    sb.append(String.format("转自" + strA, mTopic.getRetopic().getUser().getUsername(), mTopic
                            .getRetopic().getHText()));
                    if (!TextUtils.isEmpty(mTopic.getRetopic().getPic_a())) {
                        sb.append(strB).append(mTopic.getRetopic().getPic_a()).append("\n");
                    }
                }
                sb.append(strC);
                localIntent.putExtra("sms_body", sb.toString());
                startActivity(localIntent);
            } else if (str2.equals(getString(R.string.email))) {
                Intent localIntent = new Intent("android.intent.action.SEND");
                StringBuilder sb = new StringBuilder();
                if (!TextUtils.isEmpty(mTopic.getRetopic().getTid())) {
                    sb.append(String.format(strA, mTopic.getRetopic().getUser().getUsername(), mTopic.getRetopic()
                            .getHText()));
                    if (!TextUtils.isEmpty(mTopic.getRetopic().getPic_a())) {
                        sb.append(strB).append(mTopic.getRetopic().getPic_a()).append("\n");
                    }
                } else {
                    sb.append(String.format(strA, mTopic.getUser().getUsername(), mTopic.getHText()));
                    if (!TextUtils.isEmpty(mTopic.getPic_a())) {
                        sb.append(strB).append(mTopic.getPic_a()).append("\n");
                    }
                }
                sb.append(strC);
                localIntent.putExtra("android.intent.extra.TEXT", getString(R.string.mail_body_text, sb.toString()));
                localIntent.putExtra("android.intent.extra.SUBJECT", getString(R.string.mail_subject));
                localIntent.setType("application/octet-stream");
                startActivity(Intent.createChooser(localIntent, getString(R.string.choose_email_client)));
            }
        }
    }
}
